const { commentTable, articleTable } = require('../../schemas/index');

const { getResJson, formatTime } = require('../../assets/util');

/**
 * 添加评论
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 */
exports.addComment = (params, callback) => {
    params.commentTime = params.compareDate = formatTime(new Date(),'YYYY-MM-DD');
    commentTable.insertMany(params, (err, data) => {
        let resJson = {};
        if (err) {
            resJson = getResJson(data, '评论失败', false);
        } else {
            articleTable.updateOne({ _id: params.articleId }, { $inc: { commentTotal: 1 } },err => {
                if(err){
                    console.log('---------');
                    console.log(err);
                    console.log(`${params.articleTitle} - 评论总数自增失败`);
                    
                }
            })
            resJson = getResJson(data, '评论成功');
        }
        callback(resJson);
    })
}

/**
 * 通过文章ID去查询评论
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 */
exports.searchComment = (params, callback) => {
    commentTable.find({ articleId: params.articleId }, (err, data) => {
        let resJson = {};
        if (err) {
            resJson = getResJson(data, '查询失败', false);
        } else {
            resJson = getResJson(data, '查询成功');
        }
        callback(resJson);
    }).sort({
        commentTime: -1
    })
}